home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / RLaB 1.15c / examples / curve_fit.r < prev    next >
Encoding:
Text File  |  1994-09-20  |  1.1 KB  |  62 lines  |  [TEXT/RLAB]

  1. //
  2. // curve_fit.r
  3. //
  4.  
  5. // Use a minimization scheme to fit a model to a set of data
  6. // points.
  7.  
  8. // Create the data...
  9.  
  10. x = (0:10:.1)';
  11. y = 3.2.*1.5.^x;
  12.  
  13. ptitle ("Original Contrived Data");
  14. plot ([x,y]);
  15. pause ();
  16.  
  17. // Now add some random-ness
  18.  
  19. rand ("uniform", -max(abs(y))/5, max(abs(y))/5);
  20. y_orig = y;
  21. y = y + rand (size (y));
  22.  
  23. ptitle ("Original Data with some Random-ness Added");
  24. plot ([x,y]);
  25. pause ();
  26.  
  27. // Now make up a model function
  28.  
  29. fmodel = function (a, b, x) { return a.*b.^x; }
  30.  
  31. // Now make up a cost function
  32.  
  33. fcost = function ( A ) 
  34. {
  35.   global (x, y)
  36.   return -sum ( abs ((y - fmodel (A[1], A[2], x))).*x); 
  37. }
  38.  
  39. // Now load the min/max - imizer
  40.  
  41. rfile mdsmax
  42. rfile nmsmax
  43.  
  44. #fit = nmsmax (fcost, [1, 1]);
  45. fit = mdsmax (fcost, [1, 1]);
  46.  
  47. // Plot the result
  48.  
  49. ptitle ("Original+Random-ness and Fitted Model");
  50. plot ([ x, y, fmodel (fit.x[1], fit.x[2], x) ]);
  51. pause ();
  52.  
  53. ptitle ("Original and Fitted Model");
  54. plot ([ x, y_orig, fmodel (fit.x[1], fit.x[2], x) ]);
  55.  
  56. "\tNow compare original model coefficients and fitted"
  57.  
  58. original = [3.2, 1.5]
  59. fitted = fit.x
  60.  
  61. difference = [3.2, 1.5] - fit.x
  62.